<?php
/**
 * Created by PhpStorm.
 * User: HuangLuSen
 * Date: 2017/5/3
 * Time: 14:49
 */

namespace app\admin\controller;


use app\admin\model\Users;
use app\common\controller\Base;
use app\common\traits\Wechat;
use think\App;
use think\facade\Session;
use think\facade\Cache;

class Login extends Base
{
    use Wechat;

    public function _initialize()
    {
        parent::_initialize();
    }
    public function index(){
        $this->redirect('login');
    }
    /**
     * 登陆显示
     * @return mixed
     */
    public function login(){
        if ($this->getBower())return $this->fetch('ie');
        if (is_login()) $this->redirect('admin/index/index');
        return $this->fetch();
    }

    public function loginadmintest(){
        if ($this->getBower())return $this->fetch('ie');
        if (is_login()) $this->redirect('admin/index/index');
        return $this->fetch();
    }

    /**
     *登陆验证
     */
    public function checklogin(){
        if (!request()->isAjax())$this->error("提交方式错误！",url('admin/Login/login'));
        $admin_username=input('username');
        $password=input('password');
        $user  = new Users();
        if($user->login($admin_username,$password)){
            if(isMobile())$this->success('恭喜您，登陆成功',url('mobile/Index/index'));
             $this->success('恭喜您，登陆成功',url('admin/Index/index'));
        }else{
            $this->error($user->getError(),url('admin/Login/login'));
        }
    }

    /**
     * 发送微信验证码
     */
    public function sendYanzheng()
    {
        $username = $this->request->param('username');
        if(is_numeric($username)){
            $where['phone'] = $username;
        } else {
            $where['username']=$username;
        }
        $data= Users::get($where);
        if (empty($data)) {
            $this->error('用户名或者密码错误！');
        }else{
            if($data['status']!=1){
                $this->error('该账号已被禁用！请联系管理员！');exit;
            }
            if($data['weixinstatus']!=1){
                $this->error('请绑定微信公众号之后在登陆系统！');exit;
            }
        }
        $code = rand(1000,9999);
        $str = [
            'touser'=>$data['openid'],
            'template_id'=> config('admin.weixin.verif_code'),
            'url'=>'',
            'data'=>[
                'first'=>['value'=> $username.' 您的登陆验证码信息如下:','color'=>'#173177'],
                'keyword1'=>['value'=>config('admin.company.title')."登陆验证码",'color'=>'#173177'],
                'keyword2'=>['value'=>$code,'color'=>'#FF0000'],
                'keyword3'=>['value'=>date("Y-m-d H:i:s",time()+30),'color'=>'#173177'],
                'remark'=>['value'=>"感谢使用".config('admin.company.title'),'color'=>'#173177'],
            ]
        ];
        $re = $this->sendWexin($str,$data['id']);
        if($re['errmsg']=='ok'){
            session('user_'.$data['id'],$code);
            $this->success('微信验证码发送成功!请注意查收');
        }else{
            $this->error('微信验证码发送失败！请联系管理员');
        }
    }

    /**
     * 微信验证码方式登录验证
     */
    public function VerifLogin(){
        if (!request()->isAjax())$this->error("提交方式错误！",url('admin/Login/login'));
        $admin_username=input('username');
        $code=input('code');
        $user  = new Users();
        if($user->verif($admin_username,$code)){
            if(isMobile())$this->success('恭喜您，登陆成功',url('mobile/Index/index'));
            $this->success('恭喜您，登陆成功',url('admin/Index/index'));
        }else{
            $this->error($user->getError(),url('admin/Login/login'));
        }
    }


    /*
	 * 清理缓存
	 */
    public function clear()
    {
        Cache::clear();
        if(config('log.clear_on')){
            // 删除指定时间的日志(默认1个月)
            $path = list_file($this->app->getRuntimePath());
            foreach ($path as $f) {
                if ($f ['isDir']) {
                    foreach (list_file($f ['pathname']) as $ff) {
                        if ($ff ['isDir']) {
                            foreach (list_file($ff['pathname']) as $fff) {
                                if ($fff ['isFile']) {
                                    @unlink($fff['pathname']);
                                }
                            }
                        }else{
                           @unlink($ff ['pathname']);
                        }
                    }
                }
            }
        }
        $this->success ('清理缓存成功');
    }
    /**
     * 退出登录
     */
    public function logout()
    {
        session('admin_user',null);
        $this->redirect('admin/Login/login');
    }

    /**
     * 修改密码
     * @return mixed
     */
    public function editpassword(){
        if($this->request->isPost()){
            $data = $this->request->post();
            //获取参数
//            dump($data);die;
            empty($data['old']) && $this->error('请输入原密码');
            empty($data['password']) && $this->error('请输入新密码');
            empty($data['repassword']) && $this->error('请输入确认密码');
            if($data['password'] !== $data['repassword']){
                $this->error('您输入的新密码与确认密码不一致');
            }
            $users = Users::get(['id'=>$data['id'],'password'=> md5($data['old'])]);
            if($users){
                $a=Users::update(['id' => $data['id'], 'password' => md5($data['password'])]);
                if($a){
                    session('admin_user',null);
                    $this->success('修改成功，请重新登陆！', url('login'));
                }else{
                    $this->error('修改失败！请联系管理员！');
                }
            }else{
                $this->error('原始密码不正确！');
            }
        } else {
            $id = session('admin_user.adminid');
            $this->assign("id",$id);
            return $this->fetch();
        }
    }
}